package com.example.springboot_test.easyexcel.handler;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.write.handler.SheetWriteHandler;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.metadata.holder.WriteWorkbookHolder;
import com.example.springboot_test.common.poi.util.POIExcelUtil;
import com.example.springboot_test.easyexcel.model.WaterMarkModel;
import com.example.springboot_test.easyexcel.model.common.SheetModel;
import org.apache.poi.xssf.usermodel.XSSFSheet;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 自定义水印处理器
 *
 * @author xudongmaster
 */
public class CustomWaterMarkHandler implements SheetWriteHandler {

    /**
     * sheet页名称列表
     */
    private List<String> sheetNameList;
    /**
     * 水印信息
     */
    private List<WaterMarkModel> waterMarkList = new ArrayList<>();


    public CustomWaterMarkHandler(List<WaterMarkModel> waterMarkList) {
        if (CollUtil.isEmpty(waterMarkList)) {
            return;
        }
        this.waterMarkList = waterMarkList.stream().filter(x ->
                StrUtil.isNotBlank(x.getSheetName()) && x.getWaterMarkBytes() != null && x.getWaterMarkBytes().length > 0)
                .collect(Collectors.toList());
        sheetNameList = this.waterMarkList.stream().map(SheetModel::getSheetName).distinct().collect(Collectors.toList());
    }

    @Override
    public void beforeSheetCreate(WriteWorkbookHolder writeWorkbookHolder, WriteSheetHolder writeSheetHolder) {

    }

    /**
     * sheet页创建之后调用
     *
     * @param writeWorkbookHolder 文档对象
     * @param writeSheetHolder    sheet页对象
     */
    @Override
    public void afterSheetCreate(WriteWorkbookHolder writeWorkbookHolder, WriteSheetHolder writeSheetHolder) {
        XSSFSheet sheet = (XSSFSheet) writeSheetHolder.getSheet();
        //不需要添加水印，或者当前sheet页不需要添加水印
        if (CollUtil.isEmpty(waterMarkList) || !sheetNameList.contains(sheet.getSheetName())) {
            return;
        }
        //获取当前sheet的水印
        List<WaterMarkModel> sheetWaterMarkList = waterMarkList.stream().filter(x ->
                StrUtil.equals(x.getSheetName(), sheet.getSheetName())
        ).collect(Collectors.toList());
        //当前sheet页不需要水印
        if (CollUtil.isEmpty(sheetWaterMarkList)) {
            return;
        }
        for (WaterMarkModel waterMarkModel : sheetWaterMarkList) {
            //水印数据
            byte[] waterMarkBytes = waterMarkModel.getWaterMarkBytes();
            //插入水印
            POIExcelUtil.insertWaterRemark(sheet, waterMarkBytes);
        }
        //删除冻结行列信息
        waterMarkList.removeAll(sheetWaterMarkList);
        sheetNameList = waterMarkList.stream().map(SheetModel::getSheetName).distinct().collect(Collectors.toList());
    }
}